<?php

    class Router {

        private $ROUTE;
        private $CONTROLLERS;
        private $VIEW;
        private $URL;

        function __construct() {
            $this->URL = $_SERVER['REQUEST_URI'];
            $this->CONTROLLERS = scandir(__DIR__.'/controller');
            $this->VIEW = scandir(__DIR__.'/view');

            $this->createRoute();
            $this->validURL($this->URL);

            if (isset($this->ROUTE[$this->URL])){
                foreach ($this->ROUTE[$this->URL] as $key => $item){
                    if (file_exists(__DIR__.'/view/'.$item)){
                        include __DIR__.'/view/'.$item;
                    }
                    if (file_exists(__DIR__.'/controller/'.$item)){
                        include __DIR__.'/controller/'.$item;
                        $controllerAction = str_replace(".php", "", $item);
                        new $controllerAction();
                    }
                }
            } else {
                include __DIR__.'/view/index.php';
                include __DIR__.'/controller/indexController.php';
                new indexController();
            }
        }

        protected function addRouter($url, $controller, $view) {
            $this->ROUTE[$url] = [$controller.'Controller.php', $view.'.php'];
        }

        public function createRoute(){
            foreach ($this->CONTROLLERS as $key => $item){
                $controller = str_replace('Controller.php', '', $item);
                if ($item == '.' || $item == '..' ){
                    continue;
                };
                foreach ($this->VIEW as $key => $item){
                    $view = str_replace('.php', '', $item);
                    if ($item == '.' || $item == '..' ){
                        continue;
                    } else if ($controller == $view) {
                        $this->addRouter('/'.$controller, $controller, $view);
                    }
                }
            }
        }

        protected function validURL ($URL) {
//            print_r(explode("/", $URL));
            $URL = explode("/", $URL);
            unset($URL[0]);
            print_r($URL);
        }
    }